// 付款登记弹窗
<template>
  <div class="addDialog basic-from">
    <el-dialog
      custom-class="small-padding-dialog"
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="1200px"
      @close="handleDialogClosed"
    >
      <el-form ref="dialogForm" :rules="rules" :model="formData" class="form-wrap">
        <h4 class="dialogItemTitle full">付款信息</h4>
        <el-form-item label="工程名称" prop="engineeringName">
          <el-button class="add" type="primary" size="mini" @click="chooseEngineering" v-if="type == 'add'">选择工程合同</el-button>
          <el-input v-halfCharCode v-model="formData.engineeringName" readonly />
        </el-form-item>
        <el-form-item label="物业名称" prop="propertyName">
          <el-input v-halfCharCode v-model="formData.propertyName" readonly />
        </el-form-item>
        <el-form-item label="付款方式" prop="paymentWay" class="full">
          <el-input v-halfCharCode v-model="formData.paymentWay" readonly type="textarea" />
        </el-form-item>
        <h4 class="dialogItemTitle full">
          本次付款信息
          <em v-if="residueAmount != ''">未付金额: {{residueAmount | thousandMoney}}元</em>(有结算时以结算为准，没有结算时以合同为准)
        </h4>
        <div class="inlineInputGroup full">
          <span>第</span>
          <el-form-item prop="payNumber">
            <el-input v-halfCharCode :readonly="type === 'preview'" v-model.number="formData.payNumber" />
          </el-form-item>
          <span>次 付款支付日期</span>
          <el-form-item prop="payDate">
            <el-date-picker
              type="datetime"
              v-model="formData.payDate"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              placeholder="请输入支付日期"
              :readonly="isReadonly"
							:picker-options="pickerOptions"

            />
          </el-form-item>
          <span>支付金额</span>
          <el-form-item class="flexInputItem" prop="payAmount">
            <el-input v-halfCharCode oninput="value = value.replace(/[^0-9.]/g,'')" v-if="type !== 'preview'" v-model="formData.payAmount">
              <i slot="suffix" class="el-input__icon">元</i>
            </el-input>
            <el-input readonly :value="formData.payAmount  | thousandMoney" v-else>
              <i slot="suffix" class="el-input__icon">元</i>
            </el-input>
          </el-form-item>
        </div>

        <h4 class="full">历史付款记录</h4>
        <el-table ref="multipleTable" align="left" :data="payHistory" class="full">
          <el-table-column label="单位类型" prop="payObjectType">
            <template slot-scope="scope">{{getCompanyName(scope.row.payObjectType)}}</template>
          </el-table-column>
          <el-table-column label="单位名称" prop="payObject" />
          <el-table-column label="付款次数" prop="payNumber" />
          <el-table-column label="付款金额" prop="payAmount" :formatter="priceFormatter" />
          <el-table-column label="付款日期" prop="payDate" />
        </el-table>
      </el-form>

      <!-- 工程选择弹窗 -->
      <propertyChooseDialog ref="engineeringChoose" dialogType="payment" @changeProperty="handleEngineeringChange" />
      <div slot="footer">
        <el-button @click="$bus.$emit('operationLog',formData.obtId)" v-if="type==='preview'">操作日志</el-button>
        <el-button size="small" @click="dialogVisible = false">关闭</el-button>
        <el-button size="small" v-if="type !== 'preview'" type="primary" v-throttle="[save]" :loading="saveLoading">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import { changeOperationpayitem, getPaymentHistory, } from "@/views/wy-operate/api/repair.js";
import { mapState } from "vuex";
export default {
  name: "addDepartment",
  components: {
    propertyChooseDialog,
  },
  inject: ["initList"],
  data () {
    var validateResidueAmount = (rule, value, callback) => {
      if (parseFloat(value) > parseFloat(this.residueAmount)) {
        callback(new Error('付款金额不能超过未付金额'))
      }
      callback()
    };
    return {
      type: "add", //弹窗类型，默认新增
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        //工程名称(不可编辑)
        engineeringName: "",
        // 物业名称(不可编辑)
        propertyName: "",
        // 付款方式(不可编辑)
        paymentWay: "",
        //付款日期
        payDate: "",
        //付款次数
        payNumber: "",
        //付款金额
        payAmount: "",
        // 付款id(不可编辑)
        payId: "",
        // 支付对象（施工单位名称）(不可编辑)
        payObject: "",
        // 支付对象类型（供应商类型）(不可编辑)
        payObjectType: "",
      },
      // 校验规则
      rules: {
        engineeringName: [{ required: true, message: "工程名称不能为空", trigger: "blur" }],
        propertyName: [{ required: true, message: "工程名称不能为空", trigger: "blur" }],
        paymentWay: [{ required: true, message: "付款方式不能为空", trigger: "blur" },],
        payNumber: [
          { required: true, message: "付款次数不能为空", trigger: "blur" },
          { type: 'number', min: 1, message: "付款次数不能小于0", trigger: "blur" },
        ],
        payDate: [{ required: true, message: "支付日期不能为空", trigger: "blur" },],
        payAmount: [
          { required: true, message: "支付金额不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
          { validator: validateResidueAmount, trigger: "blur" },
        ],
      },
      // 保存按钮loading
      saveLoading: false,
      // 付款记录
      payHistory: [],
      // 付款总金额
      totalAmount: 0,

			approvalAmount:0,
      // 未付金额
      residueAmount: '',

			pickerOptions: {
				disabledDate:function disabledDate(time){
					//return time.getTime() < Date.now() // 选当前时间之后的时间
					return time.getTime() > Date.now() // 选当前时间之前的时间
				}
			}
    };
  },
  computed: {
    ...mapState({
      // 公司类型列表
      companyDict: (state) =>
        state.dict.find((item) => item.type === "provider_type") || {
          children: [],
        },
    }),
    // 弹窗标题计算
    dialogTitle () {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增",
      }[this.type];
    },
    // 判断是否只读
    isReadonly () {
      return ["preview"].includes(this.type);
    },
    // 获取未付金额
    // residueAmount() {
    //   if(this.payHistory.length) {
    //     return this.payHistory[0].residueAmount
    //   } else {
    //     return this.totalAmount
    //   }
    // },
  },
  methods: {
    //开启弹窗
    show ({ type, data = {} }) {
      if (["preview", "edit"].includes(type)) {
        this.formData = data;
        this.totalAmount=data.totalAmount;
        this.approvalAmount=data.approvalAmount;
        this.getPaymentHistory(data.payId);
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 提交新增
    save () {
      if (["edit", "add"].includes(this.type)) {

        this.$refs.dialogForm.validate((valid) => {
          const { payNumber, payAmount, payDate, payId, payObject, payObjectType, itemId } = this.formData;
          let params = {
            payNumber,
            payAmount: parseFloat(payAmount),
            payDate,
            payId,
            payObject,
            payObjectType,
            itemId: this.type == 'add' ? '' : itemId
          };
          if (valid) {
            this.saveLoading = true;
            changeOperationpayitem(params, this.type).then((res) => {
              if (res.data.code == 0) {
                this.$message.success(`${this.dialogTitle}成功!`);
                this.initList({ current: 1, engineeringName: "" });
                this.dialogVisible = false;
              } else {
                this.$message.error(res.data.msg)
              }
            }).finally(() => {
              this.saveLoading = false;
            });
          }

        });
      }
    },

    // 选择工程名称
    chooseEngineering () {
      this.$refs.engineeringChoose.show("payitem");
    },
    // 监听工程改变
    async handleEngineeringChange (data) {
      const { payId, engineeringName, propertyName, unitType, unitName, payMethod, totalAmount,approvalAmount } = data;

			this.totalAmount = totalAmount;
			this.approvalAmount=approvalAmount;
			//获取付款记录
			this.getPaymentHistory(payId);

      this.formData = {
        ...this.formData,
        engineeringName,
        payId,
        propertyName,
        paymentWay: payMethod,
        payObject: unitName,
        payObjectType: unitType,
      };


    },
    // 获取付款记录
    getPaymentHistory (payId) {
      getPaymentHistory(payId).then((res) => {
        if (res.data.code == 0) {
          this.payHistory = res.data.data;
          //this.residueAmount = res.data.data.length ? res.data.data[0].residueAmount : this.totalAmount
					//如果有结算金额，则代替总金额
					//alert(approvalAmount);
					let leftAmount=this.totalAmount;
					if(this.approvalAmount && this.approvalAmount>0){
						leftAmount=this.approvalAmount;
					}
					//根据总金额减付款记录，得出剩余
					//alert(this.payHistory.length)
					this.payHistory.forEach((value,index)=>{
						leftAmount=leftAmount-value.payAmount;
					});
					this.residueAmount=leftAmount.toFixed(2);
        }
      });
    },
    // 获取公司单位类型
    getCompanyName (unitType) {
      let companyType = this.companyDict.children.find(
        (item) => item.value == unitType
      );
      return companyType ? companyType.label : "";
    },
    // 弹窗关闭初始化
    handleDialogClosed () {
      for (var i in this.formData) {
        this.formData[i] = ''
      }
      this.payHistory = []
      this.totalAmount = ''
      this.saveLoading = false;
      this.residueAmount = ''
      this.$refs.dialogForm.resetFields()
    }
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-date-editor--datetime {
    width: 100%;
  }
}
.inlineInputGroup {
  display: flex;
  align-items: center;
  & > span {
    padding: 0 0.5em;
  }
  .el-date-editor {
    width: 200px;
  }

  span {
    line-height: 40px;
  }
}
.dialogItemTitle {
  em {
    color: #f00;
    font-style: normal;
    font-size: 14px;
  }
}
// /deep/ .flexInputItem {
//   .el-form-item__content {
//     display: flex;
//     align-items: center;
//     .el-input {
//       width: 200px;
//     }
//     & > em {
//       display: inline-block;
//       font-style: normal;
//       font-size: 13px;
//       line-height: 1;
//       margin-left: 10px;
//     }
//   }
// }
</style>
